'use strict';

const Controller = require('egg').Controller;
const url = require('url');
const querystring = require('querystring');
// const WebSocket = require('egg-websocket-plugin');
const WebSocket = require('ws');
class RrwebController extends Controller {
  async save() {
    console.log(`${new Date().getHours()}:${new Date().getMinutes()}:${new Date().getSeconds()} controller/rrweb.js save`);
    const {
      ctx,
    } = this;
    const {
      events,
      id,
    } = ctx.request.body;
    // console.log('ctx.request.body:');
    // console.log(ctx.request.body);
    const result = await ctx.service.rrweb.save(events, id);
    console.log('const result = ctx.service.rrweb.save(events)  result:');
    console.log(result);
    if (result) {
      ctx.body = {
        message: '成功',
        success: true,
      };
    } else {
      ctx.body = {
        message: '失败',
        success: false,
      };
    }

  }

  async wsFn() {
    console.log(`${new Date().getHours()}:${new Date().getMinutes()}:${new Date().getSeconds()} controller/rrweb.js ws`);
    const {
      ctx,
    } = this;
    ctx.body = {
      info: '触发成功',
    };
    try {
      const wss = new WebSocket.Server({
        port: 3036,
      });
      const data = {};
      wss.on('connection', async (ws, req) => {
        console.log('websocket 连接成功的回调');
        let {
          query,
          pathname,
        } = url.parse(req.url) || {};
        console.log('query:');
        console.log(query);
        console.log('pathname:');
        console.log(pathname);
        pathname = pathname.substring(1);
        query = querystring.parse(query);
        // 接收消息
        ws.on('message', async msg => {
          console.log(`${new Date().getHours()}:${new Date().getMinutes()}:${new Date().getSeconds()} websocket 接收到信息的回调  msg:`);
          // // 通过LZString.decompressFromBase64() 还原
          // console.log(`解压前msg.length: ${msg.length}`);
          // msg = ctx.helper.LZString.decompressFromBase64(msg);
          // console.log(`解压后msg.length: ${msg.length}`);
          msg = JSON.parse(msg);
          console.log(msg);
          console.log('msg.id:');
          console.log(msg.id);
          console.log('msg.events:');
          console.log(msg.events);
          let result;
          if (msg.events && msg.events.length > 0) {
            const events = JSON.stringify({ events: msg.events });
            result = await ctx.service.rrweb.save(events, msg.id);
            console.log('result = await ctx.service.rrweb.save(events, msg.id); result:');
            console.log(result);
          }
          wss.clients.forEach(function each(client) {
            console.log(`client.readyState: ${client.readyState}`); // client.readyState: 1
            if (client.readyState === WebSocket.OPEN) {
              data.note = '服务端返回的内容 传入的录制数据为空';
              // data.message = msg;
              data.success = false;
              if (msg.events && msg.events.length > 0) {
                data.note = `服务端返回的内容 传入的录制数据数组长度: ${msg.events.length}`;
                data.success = true;
              }
              client.send(JSON.stringify(data));
            }
          });

        });
        ws.on('close', () => {
          console.log('websocket 关闭时的回调');
        });
        ctx.body = {
          info: '正常触发',
          success: true,
        };
      });
    } catch (e) {
      console.log(e);
      ctx.body = {
        message: e,
        success: false,
      };
    }
  }

  async list() {
    console.log(`${new Date().getHours()}:${new Date().getMinutes()}:${new Date().getSeconds()} controller/rrweb.js list`);
    const {
      ctx,
    } = this;
    // this.wsFn();
    const {
      id,
    } = ctx.query;
    console.log('ctx.query:');
    console.log(ctx.query);
    const result = await ctx.model.Event.findOne({
      id,
    });
    console.log('ctx.model.Event.find()  result:');
    console.log(result);
    if (result) {
      ctx.body = {
        bean: result,
        message: '成功',
        success: true,
      };
    } else {
      ctx.body = {
        bean: result,
        message: '失败',
        success: false,
      };
    }

  }
}

module.exports = RrwebController;
